package com.fulihui.wgj.consumer.communication.event;

import com.alibaba.dubbo.config.annotation.Reference;
import com.fulihui.common.enums.EventTypeEnum;
import com.fulihui.common.result.rpc.BaseResult;
import com.fulihui.common.util.MassMsgIdUtil;
import com.fulihui.wgj.facade.msg.EventMsg;
import com.fulihui.wgj.facade.request.mass.MassLogSendUpdateRequest;
import com.fulihui.wgj.facade.service.mass.WxMassLogService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author: LiuJie
 * @version: 2018/8/2 16:43
 * @description: 群发消息完成事件回执消息
 */
@Component
@Slf4j
public class MassMsgSuccessProcessor implements EventMsgProcessor{

    @Autowired
    private MassMsgIdUtil massMsgIdUtil;
    @Reference(version = "1.0.0")
    private WxMassLogService wxMassLogService;

    /**
     * 事件消息处理
     *
     * @param message 消息模型
     */
    @Override
    public void process(EventMsg message) {
        String massMsgID = message.getMassMsgID();
        if(StringUtils.isBlank(massMsgID)){
            log.error("微信事件-群发消息 MsgId 为空 ，msgId={}",massMsgID);
        }
        String recordId = massMsgIdUtil.getRecordId(massMsgID);
        if(!NumberUtils.isParsable(recordId)){
            log.error("群发消息完成回执，record ID 不规范或不存在，msgId={},recordId={}",massMsgID,recordId);
            return;
        }

        MassLogSendUpdateRequest request = new MassLogSendUpdateRequest();
        request.setId(Long.valueOf(recordId));
        request.setSuccessTotal(message.getSentCount().longValue());
        request.setFailTotal(message.getTotalCount().longValue()-message.getSentCount());
        //累加成功失败数
        BaseResult baseResult = wxMassLogService.updateMassLogAccumulate(request);
        if(baseResult.isSuccess()){
            log.info("群发消息回执，数据累加成功！request={}",request);
        }else {
            log.error("群发消息回执，数据累加失败！request={}",request);
        }
    }

    /**
     * 消息类型, 用于注册到处理器集合中, 业务方法通过对应event获取到该处理器
     *
     * @return 类型字符串
     * @see EventTypeEnum
     */
    @Override
    public String getEvent() {
        return EventTypeEnum.MASSSENDJOBFINISH.getCode();
    }
}
